package com.lfs.dispatcher.message;

import com.lfs.common.cache.redis.base.StringCache;
import com.lfs.dispatcher.charge.service.ApiDisChargeService;
import com.lfs.dispatcher.constant.DispatcherConstant;
import com.lfs.dispatcher.util.JacksonUtils;
import com.lfs.interfaces.model.dto.OrderDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author linxi
 * <p>
 * 2020年3月9日
 * TODO 处理mq中订单，将订单发送到上游
 */
@Component("messageDelegateChannel")
public class MessageDelegateChannel implements ChannelAwareMessageListener {
    private Logger logger = LoggerFactory.getLogger(MessageDelegateChannel.class);

    @Autowired
    private ApiDisChargeService apiChargeService;

    @Value("${serverType}")
    private String serverType;

    @Autowired
    private StringCache stringCache;

    @Autowired
    private ObjectMapper objectMapper;

    public void onMessage(Message message, Channel channel) throws Exception {
        //从Redis中获取此服务是否消费mq中消息
        Object server = stringCache.get(serverType);
        if (server != null && "1".equals(server.toString())) {
            long startTime = System.currentTimeMillis();
            logger.info("【MQ获取发单请求】 开始处理..");
            // 获取此条消息的queue标识 ，应答时候使用
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            // 将消息内容转换为字符串
            String messageBody = new String(message.getBody(), "UTF-8");
            // 进行消息处理
            try {
                boolean result = dealWithMessage(messageBody);
                logger.info("【MQ获取发单请求】 处理结束：状态：{} ，总耗时 time = {}ms", result, System.currentTimeMillis() - startTime);
            } catch (Exception e) {
                logger.error("【MQ处理发单请求】,出现异常，e={}", e);
            }
            // 发送ack
            channel.basicAck(deliveryTag, false);
        } else {
            logger.error("【服务未启用】，不消费mq中消息");
        }

    }

    public boolean dealWithMessage(String message) {
        OrderDto order = JacksonUtils.readValue(message, OrderDto.class);
        if (order == null) {
            logger.info("【MQ获取发单请求】json转换订单消息失败，处理失败");
            return false;
        } else {
            //根据orderNo去查询订单状态，如果订单状态为未处理，则进行操作
            Map<String, Object> map = apiChargeService.checkState(order);
            if (map != null && DispatcherConstant.ORDER_STATUS_UN_HANDLER.equals(String.valueOf(map.get("state")))) {
                apiChargeService.charge(order);
                return true;
            } else {
                return false;
            }
        }
    }

}
